package com.gdkm.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.gdkm.daomain.Blog;
import com.gdkm.util.DataSourceUtils;

public class BlogDao {
	QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

	// 新增博客
	public int addBlog(Blog blog) throws SQLException {
		String sql = "insert into blog(title,category,num,praise,imgurl,message) values(?,?,?,?,?,?)";
		return runner.update(sql, blog.getTitle(), blog.getCategory(), blog.getNum(), blog.getPraise(),
				blog.getImgurl(), blog.getMessage());
	}
	
	// 查询所有博客
	public List<Blog> findAllBlog() throws SQLException {
		String sql = "select * from blog";
		return runner.query(sql, new BeanListHandler<Blog>(Blog.class));
	}

	//查询所有图片博客
	public List<Blog> findAllImgBlog() throws SQLException{
		String sql = "select * from blog where trim(imgurl)!='' order By createTime desc";
		return runner.query(sql, new BeanListHandler<Blog>(Blog.class));
	}
	
	//查询所有非图片博客
	public List<Blog> findAllNotImgBlog() throws SQLException{
		String sql = "select * from blog where trim(imgurl)='' order By createTime desc";
		return runner.query(sql, new BeanListHandler<Blog>(Blog.class));
	}
	
	// 根据id查找博客
	public Blog findBlogById(int id) throws SQLException {
		String sql = "select * from blog where id=?";
		return runner.query(sql, new BeanHandler<Blog>(Blog.class), id);
	}

	// 删除博客
	public int deleteBlog(int id) throws SQLException {
		String sql = "delete from blog where id=?";
		return runner.update(sql, id);
	}

	// 修改博客点击次数
	public int updateNum(Blog blog) throws SQLException {
		String sql = "update blog set num=? where id=?";
		return runner.update(sql, blog.getNum(), blog.getId());
	}

	// 修改博客点赞次数
	public int updatePraise(Blog blog) throws SQLException {
		String sql = "update blog set praise=? where id=?";
		return runner.update(sql, blog.getPraise(), blog.getId());

	}
}
